<template>
  <div class="personal-library">
    <!-- 页面头部 -->
    <div class="library-header">
      <div class="header-content">
        <h1 class="library-title">
          <BookOutlined class="title-icon" />
          个人图书馆
        </h1>
        <p class="library-subtitle">管理您的个人书籍收藏</p>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <a-card class="filter-card">
        <div class="filter-content">
          <div class="filter-item">
            <label class="filter-label">应用筛选：</label>
            <a-select
              v-model:value="selectedAppId"
              placeholder="选择应用"
              style="width: 200px"
              @change="handleAppChange"
              :loading="loading"
            >
              <a-select-option value="all">全部应用</a-select-option>
              <a-select-option :value="1">应用 1</a-select-option>
              <a-select-option :value="2">应用 2</a-select-option>
              <a-select-option :value="3">应用 3</a-select-option>
            </a-select>
          </div>

          <div class="filter-stats">
            <a-statistic
              title="书籍总数"
              :value="books.length"
              :value-style="{ color: '#1890ff' }"
            />
          </div>
        </div>
      </a-card>
    </div>



    <!-- 书籍列表 -->
    <div class="books-section">
      <a-spin :spinning="loading" tip="加载中...">
        <div v-if="books.length === 0 && !loading" class="empty-state">
          <a-empty
            description="暂无书籍"
            :image="Empty.PRESENTED_IMAGE_SIMPLE"
          >
            <template #description>
              <span class="empty-text">
                {{ selectedAppId === 'all' ? '您还没有任何书籍' : '该应用下暂无书籍' }}
              </span>
            </template>
          </a-empty>
        </div>

        <div v-else class="books-grid">
          <a-card
            v-for="book in books"
            :key="book.id"
            class="book-card"
            hoverable
            :cover="book.cover"
          >
            <template #cover>
              <div class="book-cover">
                <img
                  v-if="book.cover"
                  :src="book.cover"
                  :alt="book.title"
                  class="cover-image"
                />
                <div v-else class="default-cover">
                  <BookOutlined class="default-cover-icon" />
                </div>
                <div class="book-overlay">
                  <a-button
                    type="primary"
                    shape="circle"
                    size="large"
                    @click="handleDownload(book)"
                    :loading="downloadingBooks.has(book.id)"
                  >
                    <DownloadOutlined />
                  </a-button>
                </div>
              </div>
            </template>

            <template #actions>
              <a-tooltip title="下载书籍">
                <DownloadOutlined
                  @click="handleDownload(book)"
                  :class="{ 'downloading': downloadingBooks.has(book.id) }"
                />
              </a-tooltip>
              <a-tooltip title="查看详情">
                <EyeOutlined @click="handleViewDetail(book)" />
              </a-tooltip>
              <a-tooltip title="分享">
                <ShareAltOutlined @click="handleShare(book)" />
              </a-tooltip>
            </template>

            <a-card-meta
              :title="book.title"
              :description="book.description"
            >
              <template #title>
                <div class="book-title">
                  {{ book.title }}
                  <a-tag
                    v-if="book.isPublic === 1"
                    color="green"
                    size="small"
                    class="public-tag"
                  >
                    公开
                  </a-tag>
                  <a-tag
                    v-else
                    color="orange"
                    size="small"
                    class="private-tag"
                  >
                    私密
                  </a-tag>
                </div>
              </template>
              <template #description>
                <div class="book-description">
                  <p class="description-text">{{ book.description }}</p>
                  <div class="book-meta">
                    <span class="meta-item">
                      <DownloadOutlined />
                      {{ book.downloads }} 次下载
                    </span>
                    <span class="meta-item">
                      <CalendarOutlined />
                      {{ formatDate(book.createTime) }}
                    </span>
                  </div>
                </div>
              </template>
            </a-card-meta>
          </a-card>
        </div>
      </a-spin>
    </div>

    <!-- 书籍详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="书籍详情"
      width="600px"
      :footer="null"
    >
      <div v-if="selectedBook" class="book-detail">
        <div class="detail-cover">
          <img
            v-if="selectedBook.cover"
            :src="selectedBook.cover"
            :alt="selectedBook.title"
            class="detail-cover-image"
          />
          <div v-else class="detail-default-cover">
            <BookOutlined class="detail-default-icon" />
          </div>
        </div>
        <div class="detail-info">
          <h3 class="detail-title">{{ selectedBook.title }}</h3>
          <p class="detail-description">{{ selectedBook.description }}</p>
          <div class="detail-meta">
            <div class="meta-row">
              <span class="meta-label">应用ID：</span>
              <span class="meta-value">{{ selectedBook.appId }}</span>
            </div>
            <div class="meta-row">
              <span class="meta-label">下载次数：</span>
              <span class="meta-value">{{ selectedBook.downloads }}</span>
            </div>
            <div class="meta-row">
              <span class="meta-label">创建时间：</span>
              <span class="meta-value">{{ formatDate(selectedBook.createTime) }}</span>
            </div>
            <div class="meta-row">
              <span class="meta-label">可见性：</span>
              <span class="meta-value">
                <a-tag :color="selectedBook.isPublic === 1 ? 'green' : 'orange'">
                  {{ selectedBook.isPublic === 1 ? '公开' : '私密' }}
                </a-tag>
              </span>
            </div>
          </div>
          <div class="detail-actions">
            <a-button
              type="primary"
              @click="handleDownload(selectedBook)"
              :loading="downloadingBooks.has(selectedBook.id)"
            >
              <DownloadOutlined />
              下载书籍
            </a-button>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { message, Empty } from 'ant-design-vue'
import {
  BookOutlined,
  DownloadOutlined,
  EyeOutlined,
  ShareAltOutlined,
  CalendarOutlined
} from '@ant-design/icons-vue'
import { getMyBooks, downloadFile, type BookVO } from '@/api/ai'

// 响应式数据
const books = ref<BookVO[]>([])
const loading = ref(false)
const selectedAppId = ref<number | 'all'>('all')
const downloadingBooks = reactive(new Set<number>())
const detailModalVisible = ref(false)
const selectedBook = ref<BookVO | null>(null)

// 获取书籍列表
const fetchBooks = async () => {
  try {
    loading.value = true
    const appId = selectedAppId.value === 'all' ? undefined : selectedAppId.value as number
    const response = await getMyBooks(appId)
    
    if (response.code === 0) {
      books.value = response.data || []
    } else {
      message.error(response.message || '获取书籍列表失败')
      books.value = []
    }
  } catch (error) {
    console.error('获取书籍列表失败:', error)
    message.error('获取书籍列表失败，请稍后重试')
    books.value = []
  } finally {
    loading.value = false
  }
}

// 处理应用筛选变化
const handleAppChange = (value: number | 'all') => {
  selectedAppId.value = value
  fetchBooks()
}

// 处理书籍下载
const handleDownload = async (book: BookVO) => {
  if (!book.uri) {
    message.error('书籍文件路径不存在')
    return
  }

  try {
    downloadingBooks.add(book.id)
    message.loading(`正在下载《${book.title}》，请稍候...`, 2)
    
    // 调用下载API获取文件blob
    const blob = await downloadFile(book.uri)
    
    // 检查blob是否有效
    if (!blob || blob.size === 0) {
      throw new Error('下载的文件为空')
    }
    
    // 创建blob URL
    const url = window.URL.createObjectURL(blob)
    
    // 根据文件路径获取文件扩展名，如果没有则默认为pdf
    const fileExtension = book.uri.split('.').pop()?.toLowerCase() || 'pdf'
    const fileName = `${book.title}.${fileExtension}`
    
    // 创建隐藏的下载链接
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    link.style.display = 'none'
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    // 释放blob URL
    window.URL.revokeObjectURL(url)
    
    message.success(`《${book.title}》下载成功`)
    
    // 更新下载次数（本地显示）
    book.downloads += 1
    
  } catch (error: any) {
    console.error('下载失败:', error)
    
    // 优先处理业务错误码
    if (error.code) {
      switch (error.code) {
        case 40300:
          message.error('下载次数已达今日上限')
          break
        case 40301:
          message.error('文件不存在')
          break
        case 40302:
          message.error('没有权限下载此文件')
          break
        case 40303:
          message.error('文件已过期或被删除')
          break
        default:
          message.error(error.message || `下载失败，错误码：${error.code}`)
      }
      return
    }
    
    // 处理网络和HTTP错误
    if (error.code === 'ECONNABORTED' || error.message?.includes('timeout')) {
      message.error('下载超时，请检查网络连接或稍后重试')
    } else if (error.response?.status === 404) {
      message.error('文件不存在或已被删除')
    } else if (error.response?.status === 401) {
      message.error('未授权访问，请重新登录')
    } else if (error.response?.status === 403) {
      message.error('没有权限下载此文件')
    } else {
      message.error(`下载失败：${error.message || '未知错误'}`)
    }
  } finally {
    downloadingBooks.delete(book.id)
  }
}

// 查看书籍详情
const handleViewDetail = (book: BookVO) => {
  selectedBook.value = book
  detailModalVisible.value = true
}

// 分享书籍
const handleShare = (book: BookVO) => {
  if (book.isPublic !== 1) {
    message.warning('私密书籍无法分享')
    return
  }
  
  // 这里可以实现分享功能
  const shareUrl = `${window.location.origin}/book/${book.id}`
  
  if (navigator.clipboard) {
    navigator.clipboard.writeText(shareUrl).then(() => {
      message.success('分享链接已复制到剪贴板')
    }).catch(() => {
      message.error('复制失败，请手动复制链接')
    })
  } else {
    message.info(`分享链接：${shareUrl}`)
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}



const route = useRoute()

// 组件挂载时获取数据
onMounted(() => {
  fetchBooks()
})

// 监听路由变化，当切换到此页面时重新加载数据
watch(() => route.path, (newPath) => {
  if (newPath === '/personal-library') {
    fetchBooks()
  }
}, { immediate: true })
</script>

<style scoped>
.personal-library {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 24px;
}

.library-header {
  text-align: center;
  margin-bottom: 32px;
}

.header-content {
  background: rgba(255, 255, 255, 0.95);
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.library-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #1a1a1a;
  margin: 0 0 16px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.title-icon {
  font-size: 2.5rem;
  color: #1890ff;
}

.library-subtitle {
  font-size: 1.1rem;
  color: #666;
  margin: 0;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-label {
  font-weight: 500;
  color: #333;
}

.filter-stats {
  display: flex;
  gap: 24px;
}

.books-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.empty-state {
  padding: 60px 0;
}

.empty-text {
  color: #666;
  font-size: 16px;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.book-card {
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.book-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.book-cover {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.book-card:hover .cover-image {
  transform: scale(1.05);
}

.default-cover {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.default-cover-icon {
  font-size: 48px;
  color: #999;
}

.book-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.book-card:hover .book-overlay {
  opacity: 1;
}

.book-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.public-tag,
.private-tag {
  font-size: 12px;
}

.book-description {
  color: #666;
}

.description-text {
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.book-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.downloading {
  color: #1890ff;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 书籍详情模态框样式 */
.book-detail {
  display: flex;
  gap: 24px;
}

.detail-cover {
  flex-shrink: 0;
  width: 150px;
}

.detail-cover-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 8px;
}

.detail-default-cover {
  width: 100%;
  height: 200px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.detail-default-icon {
  font-size: 48px;
  color: #999;
}

.detail-info {
  flex: 1;
}

.detail-title {
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
}

.detail-description {
  color: #666;
  margin-bottom: 20px;
  line-height: 1.6;
}

.detail-meta {
  margin-bottom: 24px;
}

.meta-row {
  display: flex;
  margin-bottom: 8px;
}

.meta-label {
  width: 80px;
  font-weight: 500;
  color: #333;
}

.meta-value {
  color: #666;
}

.detail-actions {
  display: flex;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .personal-library {
    padding: 16px;
  }
  
  .library-title {
    font-size: 2rem;
  }
  
  .header-content {
    padding: 24px;
  }
  
  .books-grid {
    grid-template-columns: 1fr;
  }
  
  .filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .book-detail {
    flex-direction: column;
  }
  
  .detail-cover {
    width: 100%;
    text-align: center;
  }
  
  .detail-cover-image,
  .detail-default-cover {
    width: 200px;
    margin: 0 auto;
  }
  
  .stream-section {
    margin-bottom: 16px;
  }
  
  .stream-messages {
    max-height: 300px;
    overflow-y: auto;
  }
  
  .stream-message {
    margin-bottom: 8px;
  }
}


</style>